﻿using System.ComponentModel.Composition;
using MEFAddin;
using ProcedureList.Library.UI;
using SSMSProcedureList;
using MEFAddin.Interfaces;

namespace ACSR.SSMS.ProcedureList
{
    [Export(typeof(IAddInCommand))]
    public class ProcedureCommand : MEFCommand
    {
        Cache _cache;
        public override void Initialize()
        {
            _cache = new Cache();
        }
        public override void Execute()
        {
            this.LoggingAdapter.LogMessage("Procedure List Executing");
            var activeWindow = this.WindowAdapter.ActiveWindow;
            if (this.WindowAdapter.IsTextWindow(activeWindow))
            {
                var savedOffset = activeWindow.Selection.ActivePoint.AbsoluteCharOffset;
                activeWindow.Selection.SelectAll();
                var text = activeWindow.Selection.Text;
                activeWindow.Selection.Cancel();
                activeWindow.Selection.MoveToAbsoluteOffset(savedOffset);

                var methods = _cache.GetMethods(activeWindow, text);
                var frm = new FormProcedureList();
                frm.BindMethods(methods);
                frm.ShowDialog();
                if (frm.SelectedMethod != null)
                {
                    activeWindow.Selection.GotoLine(frm.SelectedMethod.Position);
                }
            }
            else
            {
                this.LoggingAdapter.LogMessage("Active window is not text");
            }
        }

        public override string CommandBarName
        {
            get { return "Procedure List"; }
        }

        public override string Name
        {
            get { return "ProcedureList"; }
        }

        public override string Text
        {
            get { return "Show Procedures"; }
        }

        public override string ToolTip
        {
            get { return "Show the current procedures"; }
        }

        public override string Bindings
        {
            get
            {
                return "Global::CTRL+G";
            }
        }
    }
}
